<template>
  <div class="title mb10">调出备料</div>
  <remote-table
    :rowKey="r => r.id"
    hasAction
    :hasRefresh="false"
    :hasReset="false"
    :hasPaginate="false"
    :showSelection="false"
    showSetting
    ref="tableOutRef"
    :columns="columns"
    v-model:value="callOutList"
  >
    <template #channelId="{ record }">
      <div v-if="state.showFlg">
        {{ record.channelStr }}
      </div>
      <a-select
        v-else
        style="width: 100%"
        v-model:value="record.channelId"
        size="small"
        allow-clear
        optionFilterProp="label"
        @change="getAvailableQuantity(record)"
      >
        <a-select-option
          placeholder="请选择"
          v-for="item in channelIdOptions"
          :value="item.value"
          :key="item.value"
          :name="item.label"
          >{{ item.label }}</a-select-option
        >
      </a-select>
    </template>
    <template #cp="{ record }">
      <div v-if="state.showFlg">
        {{ record.cp }}
      </div>
      <a-select
        v-else
        allowClear
        show-search
        placeholder="请选择"
        v-model:value="record.cp"
        class="w100p"
        :filter-option="false"
        :options="cps.value"
        @change="(val, options) => onChangeCP(val, options, record)"
        :not-found-content="fetching ? undefined : null"
        @search="val => handleSearchCP(val, record)"
      >
        <template v-if="fetching" #notFoundContent>
          <a-spin size="small" />
        </template>
      </a-select>
    </template>
    <template #skc="{ record }">
      <div v-if="state.showFlg">
        {{ record.skc }}
      </div>
      <a-select
        v-else
        allowClear
        show-search
        placeholder="请选择"
        v-model:value="record.skc"
        :filter-option="false"
        :options="skcs.value"
        :not-found-content="fetching ? undefined : null"
        @search="val => handleSearchSkc(val, record)"
        @change="(val, options) => onChangeSkc(val, options, record)"
        class="w100p"
      >
        <template v-if="fetching" #notFoundContent>
          <a-spin size="small" />
        </template>
      </a-select>
    </template>
    <template #bomVersion="{ record }">
      <div v-if="state.showFlg">
        {{ record.version }}
      </div>
      <a-select
        v-else
        style="width: 100%"
        v-model:value="record.bomVersion"
        size="small"
        allow-clear
        optionFilterProp="label"
      >
        <a-select-option
          placeholder="请选择"
          v-for="item in record.bomVersionOptions"
          :value="item.value"
          :key="item.value"
          :name="item.label"
          >{{ item.label }}</a-select-option
        >
      </a-select>
    </template>
    <template #supplierId="{ record }">
      <div v-if="state.showFlg">
        {{ record.supplierName }}
      </div>
      <a-select
        v-else
        style="width: 100%"
        v-model:value="record.supplierId"
        size="small"
        show-search
        allow-clear
        optionFilterProp="label"
        @change="getAvailableQuantity(record)"
      >
        <a-select-option
          placeholder="请选择"
          v-for="item in supplierOptions"
          :value="item.value"
          :key="item.value"
          :label="item.label"
          >{{ item.label }}</a-select-option
        >
      </a-select>
    </template>
    <template #quantity="{ record }">
      <div v-if="state.showFlg">
        {{ record.quantity }}
      </div>
      <a-input-number
        v-else
        size="small"
        placeholder="请输入"
        v-model:value="record.quantity"
        allow-clear
        @change="getChangeStock(record)"
      />
    </template>
    <template #changeStock="{ record }">
      <div v-if="state.showFlg">
        {{ record.adjustedQuantity }}
      </div>
    </template>
    <template #action="{ record }">
      <a-button type="link" @click="deleteLine(record, 2)">删除</a-button>
    </template>
  </remote-table>
  <a-button
    v-if="!state.showFlg"
    block
    size="small"
    type="dashed"
    @click="addLine(callOutList, 2)"
    class="mb10 mt10"
    >新增调出信息</a-button
  >
  <div class="title mb10 mt10">调入备料</div>
  <remote-table
    :rowKey="r => r.id"
    hasAction
    :hasRefresh="false"
    :hasReset="false"
    :hasPaginate="false"
    :showSelection="false"
    showSetting
    ref="tableInRef"
    :columns="columns"
    v-model:value="callInList"
  >
    <template #channelId="{ record }">
      <div v-if="state.showFlg">
        {{ record.channelStr }}
      </div>
      <a-select
        v-else
        style="width: 100%"
        v-model:value="record.channelId"
        size="small"
        allow-clear
        optionFilterProp="label"
        @change="getAvailableQuantity(record)"
      >
        <a-select-option
          placeholder="请选择"
          v-for="item in channelIdOptions"
          :value="item.value"
          :key="item.value"
          :name="item.label"
          >{{ item.label }}</a-select-option
        >
      </a-select>
    </template>
    <template #cp="{ record }">
      <div v-if="state.showFlg">
        {{ record.cp }}
      </div>
      <a-select
        v-else
        allowClear
        show-search
        placeholder="请选择"
        v-model:value="record.cp"
        class="w100p"
        :filter-option="false"
        :options="cps.value"
        @change="(val, options) => onChangeCP(val, options, record)"
        :not-found-content="fetching ? undefined : null"
        @search="val => handleSearchCP(val, record)"
      >
        <template v-if="fetching" #notFoundContent>
          <a-spin size="small" />
        </template>
      </a-select>
    </template>
    <template #skc="{ record }">
      <div v-if="state.showFlg">
        {{ record.skc }}
      </div>
      <a-select
        v-else
        allowClear
        show-search
        placeholder="请选择"
        v-model:value="record.skc"
        :filter-option="false"
        :options="skcs.value"
        :not-found-content="fetching ? undefined : null"
        @search="val => handleSearchSkc(val, record)"
        @change="(val, options) => onChangeSkc(val, options, record)"
        class="w100p"
      >
        <template v-if="fetching" #notFoundContent>
          <a-spin size="small" />
        </template>
      </a-select>
    </template>
    <template #bomVersion="{ record }">
      <div v-if="state.showFlg">
        {{ record.version }}
      </div>
      <a-select
        v-else
        style="width: 100%"
        v-model:value="record.bomVersion"
        size="small"
        allow-clear
        optionFilterProp="label"
      >
        <a-select-option
          placeholder="请选择"
          v-for="item in record.bomVersionOptions"
          :value="item.value"
          :key="item.value"
          :name="item.label"
          >{{ item.label }}</a-select-option
        >
      </a-select>
    </template>
    <template #supplierId="{ record }">
      <div v-if="state.showFlg">
        {{ record.supplierName }}
      </div>
      <a-select
        v-else
        style="width: 100%"
        v-model:value="record.supplierId"
        size="small"
        show-search
        allow-clear
        optionFilterProp="label"
        @change="getAvailableQuantity(record)"
      >
        <a-select-option
          placeholder="请选择"
          v-for="item in supplierOptions"
          :value="item.value"
          :key="item.value"
          :label="item.label"
          >{{ item.label }}</a-select-option
        >
      </a-select>
    </template>
    <template #quantity="{ record }">
      <div v-if="state.showFlg">
        {{ record.quantity }}
      </div>
      <a-input-number
        v-else
        size="small"
        placeholder="请输入"
        v-model:value="record.quantity"
        allow-clear
        @change="getChangeStock(record)"
      />
    </template>
    <template #changeStock="{ record }">
      <div v-if="state.showFlg">
        {{ record.adjustedQuantity }}
      </div>
    </template>
    <template #action="{ record }">
      <a-button type="link" @click="deleteLine(record, 1)">删除</a-button>
    </template>
  </remote-table>
  <a-button
    v-if="!state.showFlg"
    block
    size="small"
    type="dashed"
    @click="addLine(callInList, 1)"
    class="mb40 mt10"
    >新增调入信息</a-button
  >
  <div class="fixedBottom" v-if="!state.showFlg">
    <a-button class="mr8" @click="visible__ = false" size="small"
      >取消</a-button
    >
    <a-button type="primary" @click="saveCommit()" size="small">保存</a-button>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { cloneDeep } from 'lodash-es'
import { doc_list_supplier_post } from 'server/modules/4739'
import {
  inventory_supplier_stock_post,
  inventory_transfer_clothes_post
} from '@/server/modules/inventoryProduct'
import fetchApply from '@/server/axios'
import useAPI from 'UseApi'

const APIS = useAPI(null, [2838])
const { pro_proof_list_include_cp_post_, pro_proof_list_include_skc_post_ } =
  APIS
const fetching = ref(false)

const props = defineProps({
  visible: Boolean,
  columns: {
    type: Object,
    default: function () {
      return {}
    }
  },
  mainInfo: {
    type: Object,
    default: function () {
      return {}
    }
  },
  productInOutDetails: {
    type: Array,
    default: function () {
      return []
    }
  },
  showFlg: {
    type: Boolean,
    default: function () {
      return false
    }
  }
})

const visible__ = ref(props.visible)
const emit = defineEmits(['update:visible', 'success'])
watchEffect(() => {
  emit('update:visible', visible__.value)
})
const callOutList = ref([])
const callInList = ref([])
const supplierOptions = ref([])
const state = reactive({
  showFlg: false,
  skcParam: null
})

const cps = ref([])
const skcs = ref([])
const handleSearchCP = (value, record) => {
  // CP 字典数据
  if (record.skc === undefined || record.skc === null) {
    const { CPDictDatas } = pro_proof_list_include_cp_post_({
      pageNum: 1,
      pageSize: 200,
      cp: value.trim()
    })
    cps.value = CPDictDatas
  }
}

const onChangeCP = (value, options, record) => {
  if (options !== undefined) {
    if (record.skc === undefined || record.skc === null) {
      record.skc = options.skc
    }
  } else {
    record.skc = null
  }
  skcs.value = []
  skcs.value.push(record.skc)
  getBomVersion(record)
}

const handleSearchSkc = (value, record) => {
  // skc字典数据
  if (record.cp === undefined || record.cp === null) {
    const { skcDictDatas } = pro_proof_list_include_skc_post_({
      pageNum: 1,
      pageSize: 200,
      skc: value
    })
    skcs.value = skcDictDatas
  }
}

const onChangeSkc = (value, options, record) => {
  if (options !== undefined) {
    if (record.cp === undefined || record.cp === null) {
      record.cp = options.cp
    }
  } else {
    record.cp = null
  }
  cps.value = []
  cps.value.push(record.cp)
  getBomVersion(record)
}

const channelIdOptions = [
  { label: '独立站', value: 1 },
  { label: '多渠道', value: 2 }
]

const getSupplier = async () => {
  const { success, data } = await doc_list_supplier_post({})
  if (success) {
    const formatData = []
    if (data && data.length > 0) {
      data.forEach(item => {
        formatData.push({
          label: item.supplierName,
          value: item.id
        })
      })
    }
    supplierOptions.value = formatData
  }
}

const getAvailableQuantity = async record => {
  if (
    record.bomVersion &&
    record.skc &&
    record.channelId &&
    record.supplierId
  ) {
    const { success, data, retInfo } = await inventory_supplier_stock_post({
      supplierId: record.supplierId,
      channelId: record.channelId,
      bomVersion: record.bomVersion,
      skc: record.skc
    })
    if (success) {
      record.factoryStock = data.clothesStock
    } else {
      message.error(retInfo)
      record.factoryStock = null
    }
  } else {
    record.factoryStock = null
  }
  record.changeStock = null
  record.quantity = null
}

const getChangeStock = record => {
  const factoryStock = Number(record.factoryStock)
  const quantity = Number(record.quantity)
  if (!isNaN(factoryStock)) {
    if (record.transferType === 1) {
      if (!isNaN(quantity)) {
        record.changeStock = factoryStock + quantity
      } else {
        record.changeStock = factoryStock
      }
    } else if (record.transferType === 2) {
      if (!isNaN(quantity)) {
        record.changeStock = factoryStock - quantity
      } else {
        record.changeStock = factoryStock
      }
    }
  }
}

onMounted(() => {
  if (
    props.mainInfo !== null &&
    props.mainInfo.id !== undefined &&
    props.mainInfo.id !== null
  ) {
    const callObject = {}
    const defaultCallArr = []
    callObject.channelId = props.mainInfo.channelId
    callObject.cp = props.mainInfo.cp
    callObject.skc = props.mainInfo.skc
    callObject.version = props.mainInfo.version
    callObject.bomVersion = props.mainInfo.bomVersion
    defaultCallArr.push(callObject)
    callOutList.value = cloneDeep(defaultCallArr)
    callInList.value = cloneDeep(defaultCallArr)
    callInList.value[0].transferType = 1
    callOutList.value[0].transferType = 2
  }
  getSupplier()

  if (props.showFlg) {
    state.showFlg = true
    if (props.productInOutDetails.length > 0) {
      props.productInOutDetails.forEach(detail => {
        if (detail.transferType === 1) {
          callInList.value.push(detail)
        } else if (detail.transferType === 2) {
          callOutList.value.push(detail)
        }
      })
    }
  }

  if (callOutList.value.length > 0) {
    let outNo = 0
    callOutList.value.forEach(item => {
      item.seqNo = outNo
      item.bomVersionOptions = []
      if (item.bomVersion !== undefined && item.bomVersion !== null) {
        const outBomOption = {}
        outBomOption.label = item.version
        outBomOption.value = item.bomVersion
        item.bomVersionOptions.push(outBomOption)
      }
      outNo = outNo + 1
    })
  }
  if (callInList.value.length > 0) {
    let inNo = 0
    callInList.value.forEach(item => {
      item.seqNo = inNo
      item.bomVersionOptions = []
      if (item.bomVersion !== undefined && item.bomVersion !== null) {
        if (item.bomVersion !== undefined && item.bomVersion !== null) {
          const inBomOption = {}
          inBomOption.label = item.version
          inBomOption.value = item.bomVersion
          item.bomVersionOptions.push(inBomOption)
        }
      }
      inNo = inNo + 1
    })
  }
})

const addLine = (tableData, flg) => {
  const line = {}
  const len = tableData.length
  if (len > 0) {
    const count = tableData[len - 1].seqNo
    line.seqNo = count + 1
  } else {
    line.seqNo = 0
  }
  line.transferType = flg
  line.bomVersionOptions = []
  tableData.push(line)
}

const deleteLine = (record, flg) => {
  if (flg === 2) {
    callOutList.value = callOutList.value.filter(
      item => item.seqNo !== record.seqNo
    )
  } else if (flg === 1) {
    callInList.value = callInList.value.filter(
      item => item.seqNo !== record.seqNo
    )
  }
}

const saveCommit = async () => {
  const saveArr = []
  if (callInList.value.length > 0) {
    callInList.value.forEach(callIn => {
      saveArr.push(callIn)
    })
  }
  if (callOutList.value.length > 0) {
    callOutList.value.forEach(callOut => {
      saveArr.push(callOut)
    })
  }
  saveArr.forEach(item => {
    if (item.supplierId !== undefined && item.supplierId !== null) {
      const supplierName = supplierOptions.value.find(
        option => option.value === item.supplierId
      ).label
      item.supplierName = supplierName
    } else {
      item.supplierName = null
    }
    item.businessType = 3
  })
  let inStock = 0
  let outStock = 0
  callInList.value.forEach(item => {
    inStock = inStock + item.quantity
  })
  callOutList.value.forEach(item => {
    outStock = outStock + item.quantity
  })
  if (inStock !== outStock) {
    return message.error('调入总数量与调出总数量不一致，请重新填写。')
  }
  const { success, retInfo } = await inventory_transfer_clothes_post(saveArr)
  if (success) {
    emit('success')
    visible__.value = false
    message.success(retInfo)
  } else {
    message.error(retInfo)
  }
}

// 获取bom版本号
const getBomVersion = async record => {
  if (record.skc !== undefined && record.skc !== null) {
    record.bomVersionOptions = []
    const { success, data, retInfo } = await fetchApply(
      '/preparation-plan-mlbl/query-bom',
      { skc: record.skc }
    )
    if (success) {
      if (data !== null && data.list.length > 0) {
        data.list.forEach(item => {
          const bomOption = {}
          bomOption.label = item.versionStr
          bomOption.value = item.version
          record.bomVersionOptions.push(bomOption)
        })
        if (
          record.bomVersionOptions.length > 0 &&
          record.bomVersionOptions.length === 1
        ) {
          record.bomVersion = record.bomVersionOptions[0].value
        } else {
          record.bomVersion = null
        }
      }
    } else {
      message.error(retInfo)
    }
  } else {
    record.bomVersion = null
  }
  getAvailableQuantity(record)
}
</script>
<style lang="scss" scoped>
.fixedBottom {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e9e9e9;
  padding: 10px 16px;
  background: #fff;
  text-align: right;
  z-index: 1;
}
</style>
